package com.azkj.album.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import androidx.core.content.FileProvider;

import com.azkj.album.network.utils.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * @author : MaJi
 * @time : (9/4/21)
 * dexc :
 */
public class DownLoadApkUtils {


    /**
     * @param url 下载连接
     * @param savePath 储存下载文件的SDCard目录
     * @param listener 下载监听
     */
    public static Handler mHandler = new Handler(Looper.getMainLooper());

    public static void download(final String url, File file, final OnDownloadListener listener) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                // 下载失败
                mHandler.post(() -> listener.onDownloadFailed("下载失败"));
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                try {

                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    if (total < 0) {
                        ResponseBody responseBody = response.body();
                        BufferedSource source = responseBody.source();
                        source.request(Long.MAX_VALUE);
                        Buffer buffer = source.buffer();
                        is = buffer.clone().inputStream();
                        total = is.available();
                    }
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        float progress = (sum * 1.0f / total * 100);
                        // 下载中
                        mHandler.post(() -> listener.onDownloading(progress));
                    }
                    fos.flush();
                    // 下载完成
                    mHandler.post(() -> listener.onDownloadSuccess());
                } catch (Exception e) {
                    mHandler.post(() -> listener.onDownloadFailed("下载失败"));
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }


    /**
     * 安装app
     *
     * @param mContext
     * @param externalUrl
     * @param file
     */
    public static void installApk(Context mContext, String externalUrl, File file) {
        try {
            Intent installAppIntent = getInstallAppIntent(mContext, file, false);
            mContext.startActivity(installAppIntent);
        } catch (Exception e) {//安装出错 跳转外部浏览器下载
            if (TextUtils.isEmpty(externalUrl)) {
                ToastUtils.showCenterToast("更新失败");
                return;
            }
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(externalUrl);
            intent.setData(content_url);
            mContext.startActivity(intent);
        }
    }

    /**
     * 安装app
     *
     * @param mContex
     * @param file
     * @param isNewTask
     * @return
     */
    private static Intent getInstallAppIntent(Context mContex, final File file, final boolean isNewTask) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        String type = "application/vnd.android.package-archive";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            data = Uri.fromFile(file);
        } else {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            String authority = mContex.getPackageName() + ".provider";
            data = FileProvider.getUriForFile(mContex, authority, file);
        }
        intent.setDataAndType(data, type);
        return isNewTask ? intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) : intent;
    }


    public interface OnDownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess();

        /**
         * @param progress 下载进度
         */
        void onDownloading(float progress);

        /**
         * 下载失败
         */
        void onDownloadFailed(String msg);
    }

}
